package com.cs.peanut.base_app.service;

import android.content.Context;
import android.os.Environment;

import com.cs.peanut.base.util.TLog;
import com.cs.peanut.base_app.Servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import fi.iki.elonen.NanoHTTPD;

public class ServletImpl implements Servlet {

    private Context context;

    public ServletImpl(Context context) {
        this.context = context;
    }

    public NanoHTTPD.Response index(NanoHTTPD.IHTTPSession session) {
        return AndroidWebServer.printSuccess(new Date());
    }

    public NanoHTTPD.Response upload(NanoHTTPD.IHTTPSession session) {

        Map<String, String> files = new HashMap<String, String>();
        try {
            session.parseBody(files);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NanoHTTPD.ResponseException e) {
            e.printStackTrace();
        }
        String fileName = session.getParms().get("picture");
        Map<String,String> map = session.getParms();

        String filePath = files.get("picture");
        TLog.e(filePath);
        if(fileName != null && filePath != null) {
            File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_MOVIES), fileName+"");
            TLog.e(file.getPath());
            copyFile(filePath, file);
            return AndroidWebServer.printSuccess("success");
        }
        return AndroidWebServer.printError("参数错误");
    }

    public void copyFile(String oldPath, File file) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(file);
                byte[] buffer = new byte[1024];
                int length;
                while ( (byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                  //  TLog.e(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        }
        catch (Exception e) {
            TLog.e(e.getMessage());
        }
    }
}
